<style>
.from-div {
    background-color: white;
    margin: 4px;
    position: relative;
}
.from-title {
    border-bottom: 1px solid #e7e9e9;
    width: 100%;
    padding: 15px;
    position: relative;
}
</style>

<template>
  <div id="from-div" class="from-div">
      <Spin size="large" fix v-if="spinShow"></Spin>
      <Row>
          <Col span="24">
            <div class="from-title">
                <h3>管理员编辑</h3>
            </div>
          </Col>
      </Row>
      </br>
      <Row>
          <Col span="18" offset="3">
            <div id="from-item">
                <Form ref="addFrom" label-position="top" :model="item" :rules="rules">
                    <FormItem label="用户名" prop="username" required>
                        <Input ref="username" v-model="item.username" disabled readonly></Input>
                    </FormItem>
                    <FormItem label="邮箱" prop="email">
                        <Input ref="email" v-model="item.email" placeholder="请输入邮箱"></Input>
                    </FormItem>
                    <FormItem v-if="admin.id===1" label="公司选择" prop="companyId" required >
                         <Select
                            clearable
                            ref="companyId"
                            placeholder="请输关键词搜索......"
                            v-model="item.companyId"
                            filterable
                            remote
                            :remote-method="remoteCompany"
                            :loading="sloading">
                            <Option v-for="(con, index) in companies" :value="con.id" :key="index">{{con.name}}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="角色" prop="roleId" required>
                        <Select :disabled="item.id === admin.id" placeholder="请选择角色" v-model="item.roleId">
                            <Option  v-for="role in roles" :value="role.id" :key="role.id">{{role.roleName}}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="手机号" prop="mobile">
                        <Input ref="mobile" v-model="item.mobile" placeholder="请输入手机号"></Input>
                    </FormItem>
                    <FormItem label="状态" prop="status">
                        <RadioGroup v-model="item.status">
                            <Radio :label=1>启用</Radio>
                            <Radio :label=2>禁用</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem>
                        <Button :loading="saveLoading" type="primary" @click="handleSubmit">保存</Button>
                    </FormItem>
                </Form>
            </div>
          </Col>
      </Row>
  </div>
</template>

<script>
export default {
    data () {
        const validateMobile = (rule, value, callback) => {
            if(value && !(/^1[34578]\d{9}$/.test(value))){
                callback(new Error('请输入正确的手机号码'));
            } else {
                callback()
            }
        };
        const validateEmail = (rule, value, callback) => {
            var re = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/; 
            if (value && !re.test(value)) {
                callback(new Error('请输入正确的邮箱地址'));
            } else {
                callback();
            }
        };
        return {
            admin: {},
            createUser: '',
            spinShow: false,
            saveLoading: false,
            sloading: false,
            companies: [],
            roles: [],
            item: {
                id: '',
                username: '',
                email: '',
                roleId: '',
                companyId: '',
                mobile: '',
                status: ''
            },
            rules: {
                roleId: [
                    {required: true, type: 'number', message: '请选择角色', trigger: 'change'}
                ],
                companyId: [
                    {required: true, type: 'number', message: '请选择公司', trigger: 'change'}
                ],
                mobile: [
                    { validator: validateMobile, trigger: 'blur' }
                ],
                email: [
                    { validator: validateEmail, trigger: 'blur' }
                ],
            }
        };
    },
    methods: {
        init () {
            this.admin = JSON.parse(localStorage.admin);
            if(this.admin.id===1){ this.remoteCompany('NAN') }
            this.spinShow = true;
            this.item.id = this.$route.params.id;
            this.$get('/user/info/' + this.item.id)
                .then(res => {
                    this.item.id = res.id;
                    this.item.username = res.username;
                    this.item.email = res.email;
                    this.item.roleId = res.roleId;
                    this.item.companyId = res.companyId;
                    this.item.mobile = res.mobile;
                    this.item.status = res.status;
                    this.getRole(res.companyId);
                })
                .catch(error => {
                    this.spinShow = false;
                    this.$Message.error(error.message);
                });
        },
        getRole (id) {
            this.$get('/role/select?companyId=' + id)
                .then(res => {
                    this.roles = res;
                    this.spinShow = false;
                })
                .catch(error => {
                    this.spinShow = false;
                    this.$Message.error('获取角色列表失败');
                });
        },
        handleSubmit () {
            this.$refs.addFrom.validate((valid) => {
                if (valid) {
                    this.saveLoading = true;
                    this.$post('/user/update', this.item, 'json')
                        .then(res => {
                            this.$Message.success('添加成功');
                            this.saveLoading = false;
                            setTimeout(() => {
                                this.$router.push({
                                    name: 'manager-index'
                                });
                            }, 1000);
                        })
                        .catch(error => {
                            this.saveLoading = false;
                            this.$Message.error(error.message);
                        });
                } else {
                    // 获取表单域所有field
                    let fields = this.$refs.addFrom.fields;
                    // 聚焦错误表单域
                    try {
                        fields.forEach(element => {
                            if (element.validateState === 'error') {
                                // 这里的element无foucs()
                                let refName = element.prop;
                                this.$refs[refName].focus();
                                // 抛出异常跳出循环
                                foreach.break = new Error('StopIteration');
                            }
                        });
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        remoteCompany (query) {
            if (query !== '') {
                if(query==='NAN'){query=''}
                this.sloading = true;
                this.$post('/company/search', {name: query})
                    .then(res => {
                        this.sloading = false;
                        this.companies = res;
                        this.item.roleId = '';
                        if (res.length === 1) { // 选择公司后获取该公司下的角色
                            this.getRole(res[0].id);
                        }
                    })
                    .catch(fail => {
                        this.sloading = false;
                    });
            } else {
                this.protocols = [];
                this.sloading = true;
            }
        }
    },
    created () {
        this.init();
    }
};
</script>
